package com.sanerzone.smscenter.biz.task;

import com.google.common.collect.Maps;
import com.sanerzone.smscenter.biz.entity.SmsSubmitSync;
import com.sanerzone.smscenter.biz.mapper.SmsSubmitSyncMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 网关提交响应
 * @author zhangjie
 */
@Service
@Lazy(false)
public class SmsSubmitSyncTask {
	Logger logger = LoggerFactory.getLogger(SmsSubmitSyncTask.class);
	@Autowired
	private SmsSubmitSyncMapper smsSubmitSyncMapper;
	@Autowired
    private SqlSessionFactory sqlSessionFactory;
	
	/**
	 * 延时一分钟执行一次
	 */
	@Scheduled(cron = "0 0/1 * * * ? ")
	public void execSync()
	{
		logger.info("网状状态回执，同步任务执行中...");
		List<SmsSubmitSync> list = smsSubmitSyncMapper.findList(new SmsSubmitSync());
		if (null != list)
		{
			SqlSession sqlSession = sqlSessionFactory.openSession();
			try{

				Map<String,Object> map = Maps.newHashMap();
				int count=0;
				for (SmsSubmitSync para : list)
				{
					map = Maps.newHashMap();
					map.put("gatewayStatus", para.getResult());
					map.put("submitTime", para.getCreatetime());
					map.put("reportTime", para.getCreatetime());
					map.put("tableName", getTableIndex( para.getBizid() ));
					map.put( "sendStatus",para.getSendStatus() );
					if (para.getSendStatus().startsWith( "F" )){
						map.put( "failReason",para.getReserve());
					}else if (para.getSendStatus().startsWith( "D" )){
						map.put( "waitReason",para.getReserve());
					}else if (para.getSendStatus().startsWith( "X" )){
						map.put( "waitReason",para.getReserve());
					}
					map.put( "mtBatch",para.getMtBatch() );

					map.put( "phone",para.getPhone() );
					map.put( "gatewayId",para.getGatewayId() );

					int update = sqlSession.update("com.sanerzone.smscenter.biz.mapper.SmsSendMapper.batchUpdateGatewayStatusTask", map);
					if (update == 1)
					{
						count++;
						if (count%500==0){
							sqlSession.commit();
						}
						smsSubmitSyncMapper.delete(para);
						logger.info( "异步库更新状态执行成功,mt批次{},phone:{}",para.getMtBatch(),para.getPhone());
					}

				}

			}catch (Exception e){
				e.printStackTrace();
			}finally {
				if (sqlSession != null)
				{
					sqlSession.close();
				}
			}

			

		}
	}
	//根据任务id 找到表
	public String getTableIndex(String taskId){
		String tableIndex=null;
		try{
			Date date=new Date();
			SimpleDateFormat sdf=new SimpleDateFormat("MMdd" );
			SimpleDateFormat sdfDay=new SimpleDateFormat( "dd" );
			String nowDateStr= sdf.format( date );

			Date  chooseDate=  sdf.parse( taskId.substring( 0,4 ));
			int offset=(int)(chooseDate.getTime()-date.getTime())/1000/60/60/24;
			if (offset>=-4){
				//4天以内  直接去找日表
				String sdfDaySearch=sdfDay.format( chooseDate );
				if(sdfDaySearch.charAt( 0 )=='0'){
					sdfDaySearch=sdfDaySearch.charAt( 1 )+"";
				}

				tableIndex="sms_send_"+sdfDaySearch;


			}else {
				String month=taskId.substring( 0,2 );
				tableIndex="sms_send_history_"+"2018"+month;

			}
		}catch (Exception e){
			e.printStackTrace();
			return null;
		}
		return tableIndex;
	}

	public SmsSubmitSyncMapper getSmsSubmitSyncMapper() {
		return smsSubmitSyncMapper;
	}

	public void setSmsSubmitSyncMapper(SmsSubmitSyncMapper smsSubmitSyncMapper) {
		this.smsSubmitSyncMapper = smsSubmitSyncMapper;
	}

	public SqlSessionFactory getSqlSessionFactory() {
		return sqlSessionFactory;
	}

	public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
		this.sqlSessionFactory = sqlSessionFactory;
	}

}
